<template>
  <div class="app-container">
    <div class="customContainer age-component__scroll" style="overflow-x:hidden;overflow-y:scroll;">
      <el-form :inline="true" :model="formInline" class="search-form-inline" size="small">
        <dj-gift-channel-select :from="formInline.from" :usedfor="usedfor" @change="supplierOperationChanged" @channel="channelChanged" />
        <dj-gift-type-select @change="giftTypeChanged" />
        <dj-gift-price-select @change="priceChanged" />
        <dj-gift-search-select @change="searchTextChanged" @keyupEnter="searchClick" />
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
      </el-form>
      <!-- 排序 -->
      <el-button :style="currentSort==0?'bordercolor:#409EFF;color:#409EFF':''" plain size="mini" @click="fetchData(0)">
        上架时间
        <i :class="sortControl.time?'el-icon-top':'el-icon-bottom'"></i>
      </el-button>
      <el-button :style="currentSort==1?'bordercolor:#409EFF;color:#409EFF':''" plain size="mini" @click="fetchData(1)">
        进货价
        <i :class="sortControl.price?'el-icon-top':'el-icon-bottom'"></i>
      </el-button>
      <!-- 列表 -->
      <div style="width:100%;">
        <ul style="padding-left:0;min-width:520px;max-width: 1500px;width:85%;">
          <li v-for="(item,index) in giftList" :key="index" style="list-style:none">
            <dj-gift-card :data="item" :from="formInline.from" :usedfor="1" :linkto="{name: gift_details_url, params:{ listDetail: item, from:
            formInline.from, routerflag: true }}" @addclick="addToCartClick" />
          </li>
        </ul>
        <dj-gift-label-select @select="labelSelected" style="width:15%;float:right;position:fixed;right:10px;" />
      </div>
      <!-- 点击加入购物车弹框 -->
      <el-dialog :visible.sync="cartDialogHandle" width="400px">
        <div style="width: 300px;margin: 0 auto">
          <span style="display:inline-block;width:100%;margin: 10px">名称：&nbsp;&nbsp;{{giftItem.name}}</span>
          <div style="display:inline-block;width:100%;margin: 10px">
            <span v-if="formInline.from==2" style="padding-right:20px">库存：&nbsp;&nbsp;{{giftItem.num}}</span>
            {{giftItem.box_num&&giftItem.box_num>0?'箱规：  '+giftItem.box_num+'个/箱':''}}
          </div>
          <div style="display:flex;align-items:center;margin: 10px">
            <span>使用区域：&nbsp;&nbsp;</span>
            <el-select v-model="area_type" style="width:150px">
              <el-option v-for="item in gift_list" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </div>
          <div style="display:flex;align-items:center;margin: 10px;margin-bottom:20px;">
            <span>数量：&nbsp;&nbsp;</span>
            <el-input-number v-model="purchase_number" :min="1" :max="formInline.from==2 ? (giftItem.num*1>999999?999999:giftItem.num*1) : 999999"
              :step="giftItem.box_num*1>0?giftItem.box_num*1:1"></el-input-number>
          </div>
        </div>
        <div style="display: flex;justify-content:center;">
          <el-button @click="cartDialogHandle = false"> 取 消 </el-button>
          <el-button type="primary" @click="addToCart()" style="margin-left: 30px"> 确 定 </el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 自定义底部 -->
    <div class="bottom_box">
      <el-badge class="item pull-right" style="position:relative">
        <router-link :to="{name:shoppingcar_url, params:{from:formInline.from,usedfor:usedfor,routerflag:1}}">
          <div style="position:absolute;background:red;margin-left:70px;width:20px;height:20px;border-radius:50%;text-align:center;margin-top:-10px"
            v-if="purchase_species>0">
            <span style="line-height:20px;color:#fff">{{purchase_species==0?'':purchase_species}}</span>
          </div>
          <img src="../../assets/images/car.png" alt="">
        </router-link>
      </el-badge>
    </div>
    <div style="position:fixed;right:30px;bottom:80px;">
      <img src="../../assets/images/top.png" @click="toTop">
    </div>
  </div>
</template>
<script>
import {
  getGiftPageSize, // 获取礼品列表总页数
  getGiftList, // 获取礼品列表
  addToCart, // 添加购物车
  cartSize // 获取购物车礼品种类
} from '@/api/common/gift_purchase.js';
import { DjGiftCard, DjGiftTypeSelect, DjGiftLabelSelect, DjGiftPriceSelect, DjGiftSearchSelect, DjGiftChannelSelect } from '@/components/gift';
export default {
  name: 'DjGiftPurchase',
  components: {
    'dj-gift-card': DjGiftCard,
    'dj-gift-type-select': DjGiftTypeSelect,
    'dj-gift-price-select': DjGiftPriceSelect,
    'dj-gift-search-select': DjGiftSearchSelect,
    'dj-gift-channel-select': DjGiftChannelSelect,
    'dj-gift-label-select': DjGiftLabelSelect
  },
  props: {
    data: {
      type: Object,
      default() {
        return {};
      }
    },
    from: {
      type: Number,
      default: 0
      // 1：供应商，2：中央仓
    },
    usedfor: {
      type: Number,
      required: true
      // 1:运管系统采购下单，2：采购平台总部下单，3：采购平台总部统配
    }
  },
  data() {
    return {
      gift_list: [
        { name: '礼品机区域', id: '1' },
        { name: '礼品柜区域', id: '2' },
        { name: '摊位机区域', id: '3' },
        { name: '企划区域', id: '4' },
        { name: '其他区域', id: '5' }
      ],
      area_type: this.$store.getters.giftDisplay,
      prefix: this.usedfor == 1 ? 'SMS_' : 'IMS_', // localstore key前缀
      scrollDiv: null, // 礼品列表父容器，用于滚动时是否滚到底
      requesting: true, // 滑动到底请求接口状态标记
      noMoreData: false, // 没有更多数据了
      noticeNoMore: false, // 控制提示礼品列表已经没有更多数据了，true为提示，false不提示
      loadingTips: '努力加载中...', // 礼品列表加载数据中提示
      listLoading: false, // 标志礼品列表当前是否在加载数据中
      giftList: [], // 礼品列表
      currentPage: 0, // 当前页数
      totalPage: 0, // 总页数
      purchase_species: 0, // 购物车，采购种类
      purchase_number: 1, // 加购物车时，采购数量
      giftItem: {}, // 当前要加购物的礼品
      cartDialogHandle: false, // 控制加购物车弹窗是否展示
      // 接口请求参数
      formInline: {
        from: this.from, //采购渠道， 1供应商，2中央仓
        docking_id: '', //对接人，在选择供应商的情况下有这个
        supplier_id: '', //供应商id，在选择供应商的情况下有这个
        first_type: '', //一级类别
        second_type: '', //二级类别
        type: '', //三级类别
        gift_id: '', //礼品id
        label_id: '', // 标签id
        no_obsolete: '', //神采编号
        gb_code: '', //国标码
        name: '', //名称
        price_low: '', //最低价
        price_high: '', //最高价
        // searchVal: "", //模糊查询的文字
        sort: '', // 排序字段，time，price
        sort_by: '' // 排序方式，asc：升序，desc：降序
      },
      currentSort: 0, // 当前选中的排序项，0，表示sortControl中第一个
      sortControl: { time: false, price: true }, // 排序值记录，false倒叙，true正序，time：上架时间排序，price：采购价排序
      hige: 0
    };
  },
  computed: {
    gift_details_url: function() {
      if (this.usedfor == 1) {
        return 'warehouse/gift_details';
      } else if (this.usedfor == 2) {
        return 'giftPurchase/cgGiftdetails';
      } else if (this.usedfor == 3) {
        return 'giftPurchase/hqGiftDetail';
      } else {
        return '';
      }
    },
    shoppingcar_url: function() {
      if (this.usedfor == 1) {
        return 'warehouse/shoppingcar';
      } else if (this.usedfor == 2) {
        return 'giftPurchase/giftcar';
      } else if (this.usedfor == 3) {
        return 'giftPurchase/hqCar';
      } else {
        return '';
      }
    }
  },
  activated() {
    // 添加滚动事件，检测滚动到页面底部
    this.scrollDiv = document.getElementsByClassName('customContainer')[0];
    // 保持滚动的高度
    this.scrollDiv.scrollTop = this.hige;
    this.area_type = this.$store.getters.giftDisplay;
    if (this.scrollDiv) this.scrollDiv.addEventListener('scroll', this.scrollBottom);
    // 刷新数据
    if (!this.giftList || this.giftList.length == 0) {
      this.fetchData();
    }
    this.refreshCart();
  },
  deactivated() {
    this.scrollDiv.removeEventListener('scroll', this.scrollBottom);
  },
  updated() {
    this.scrollDiv.scrollTop = this.hige;
  },
  methods: {
    // 采购渠道发生变化
    channelChanged(channel) {
      // ={}会有问题，因为组件中的值并没有重置
      // 暂时只清除供应商&对接人
      if (channel == 2) {
        this.formInline.supplier_id = '';
        this.formInline.docking_id = '';
      }
      // 请求后台数据之前先清空列表，避免网络慢时错乱加购物车
      this.giftList = [];
      this.formInline.from = channel;
      this.fetchData();
      this.refreshCart();
    },
    // 供应商、对接人发生变化
    supplierOperationChanged(obj) {
      for (let key in obj) this.formInline[key] = obj[key];
    },
    // 礼品标签被选择
    labelSelected(obj) {
      for (let key in obj) this.formInline[key] = obj[key];
      this.searchClick();
    },
    // 礼品类别发生变化
    giftTypeChanged(obj) {
      for (let key in obj) this.formInline[key] = obj[key];
    },
    // 价格区间发生变化
    priceChanged(obj) {
      for (let key in obj) this.formInline[key] = obj[key];
    },
    // 搜索输入框内容发生变化
    searchTextChanged(obj) {
      for (let key in obj) this.formInline[key] = obj[key];
    },
    scrollBottom() {
      //滚动到底响应事件：自动
      let maxHeight = this.scrollDiv.scrollHeight; // 可滚动最大高度
      let cliHeight = this.scrollDiv.clientHeight; // 窗口固定高度
      let scrolHeight = this.scrollDiv.scrollTop; // 当前滚动距离
      // 保存滚动高度的变量
      this.hige = this.scrollDiv.scrollTop;
      // 判断滚动到底，窗口固定高度860左右
      if (maxHeight - cliHeight - scrolHeight < 400 && this.requesting) {
        this.requesting = false; // 避免重复加载
        this.listLoading = true;
        this.loadingTips = '努力加载中...';
        if (this.currentPage > 0 && this.noMoreData) {
          // 已经是最后一页
          return;
        }
        // 请求下一页数据
        this.getNextPage();
      } else if (maxHeight - cliHeight - scrolHeight < 10) {
        if (this.noticeNoMore) {
          this.$message('没有更多了..');
          this.noticeNoMore = false;
        }
      }
    },
    toTop() {
      let scrollDiv = document.getElementsByClassName('customContainer')[0];
      scrollDiv.scrollTop = 0;
    },
    searchClick() {
      this.fetchData();
    },
    refreshCart() {
      cartSize({ type: this.formInline.from }, this.usedfor).then(response => {
        if (response) this.purchase_species = response.count;
        else this.purchase_species = 0;
      });
    },
    // 点击打开加入购物车弹框
    addToCartClick(item) {
      this.purchase_number = item.box_num > 0 ? item.box_num : 1;
      this.cartDialogHandle = true;
      this.giftItem = item;
    },
    addToCart() {
      var dt = {
        gift_id: this.giftItem.gift_id,
        shop_num: this.purchase_number,
        type: this.formInline.from,
        money: this.giftItem.money_sell,
        area_type: this.area_type
      };
      this.$store.commit('updategiftDisplay', this.area_type);
      addToCart(dt, this.usedfor).then(response => {
        if (response.code == 1) {
          this.$message({
            type: 'success',
            message: '添加成功'
          });
          this.refreshCart();
        }
      });
      this.cartDialogHandle = false;
    },
    // 列表
    fetchData(val) {
      if (val == 0) {
        this.formInline.sort = 'time';
        this.currentSort = 0;
        this.sortControl.time = !this.sortControl.time;
        this.formInline.sort_by = this.sortControl.time ? 'asc' : 'desc';
      } else if (val == 1) {
        this.formInline.sort = 'price';
        this.currentSort = 1;
        this.sortControl.price = !this.sortControl.price;
        this.formInline.sort_by = this.sortControl.price ? 'asc' : 'desc';
      } else {
        this.formInline.sort = 'time';
        this.currentSort = 0;
        this.sortControl.time = false;
        this.formInline.sort_by = this.sortControl.time ? 'asc' : 'desc';
      }
      this.requesting = true;
      this.noMoreData = false;
      this.noticeNoMore = false;
      this.currentPage = 0;
      this.totalPage = 0;
      this.getNextPage();
    },
    getNextPage() {
      this.listLoading = true;
      this.currentPage += 1;
      getGiftList(this.formInline, this.currentPage, this.usedfor)
        .then(response => {
          if (!response || response.length == 0) {
            if (this.currentPage == 1) this.giftList = [];
            this.noMoreData = true;
            this.noticeNoMore = true;
          } else if (response instanceof Array) {
            if (this.currentPage == 1) this.giftList = response;
            else this.giftList.push(...response);
          } else {
            if (this.currentPage == 1) this.giftList = [];
          }
          // 请求的数据加载完成后，再次滚动到底部时，允许继续请求数据
          this.requesting = true;
          this.listLoading = false;
        })
        .catch(res => {
          this.loadingTips = '加载失败，请稍后重试';
          this.listLoading = false;
          // 请求失败时，滚动到底部时，允许再次请求
          this.requesting = true;
        });
    },
    getTotalPageSize() {
      getGiftPageSize(this.formInline, this.usedfor).then(response => {
        this.totalPage = response;
      });
    }
  }
};
</script>

<style scoped>
.app-container .customContainer {
  color: #888;
}
.app-container .customContainer .search-form-inline {
  min-width: 1000px;
  display: block;
}
</style>